<?php


namespace App\Http\Middleware;

use Closure;
use D1M\Common\Exceptions\BusinessException;
use Firebase\JWT\JWT;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;


class AuthLogin
{
    public function handle(Request $request, Closure $next)
    {
        $this->selfToken($request);
        return $next($request);
    }

    private function jwtToken($request)
    {
        if (!$request->hasHeader('Authorization')) {
            return response()->json(['error' => 'Authorization header missing'], 401);
        }

        $header = $request->header('Authorization');
        $jwt = trim(str_replace('Bearer', '', $header));

        if(!$jwt){
            return response()->json(['error' => 'JWT not found'], 400);
        }

        try {
            $decodedToken = JWT::decode($jwt, env('JWT_KEY'), ["HS256"]);
        } catch (\Exception $e) {
            return response()->json(['error' => 'JWT is invalid'], 400);
        }

        Auth::guard('api')->setUser($decodedToken->data);
    }

    private function selfToken($request)
    {
        $token = str_replace('Bearer ', '', $request->header('Authorization'));
        Log::info('check token:'.$token);
        $data = json_decode($this->decrypt($token));
        Log::info('check token data:'.json_encode($data));
        if(!$data){
            throw new BusinessException('登录失效～',-2);
        }
        $redisKey = 'pos:self_login:token:'.$data->manage_no;
        $redis = Redis::get($redisKey);
        Log::info('check token redis:'.$redis);
        if(!$redis || $redis !=$token){
            throw new BusinessException('登录失效～',-2);
        }
        //刷新token时效
        Redis::expire($redisKey,env("USER_LOGIN_EXPIRE_TIME"));

    }

    private function decrypt($str)
    {
        return openssl_decrypt(base64_decode($str),"AES-128-ECB",env("API_SECRET_KEY"), OPENSSL_RAW_DATA);
    }
}